<?php

namespace core;

use core\lib\log;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

class wjssk
{
    const VERSION = '1.0';
    public static $classMap = [];
    private $assign;

    static public function run()
    {
        log::init();
        $route = new lib\route();
        $ctrl = $route->ctrl;
        $action = $route->action;
        $ctrl_file = APP . '/ctrl/' . $ctrl . '.php';
        $ctrl_class = MODULE . '\ctrl\\' . $ctrl;
        if (is_file($ctrl_file)) {
            include $ctrl_file;
            $ctrl = new $ctrl_class();
            $ctrl->$action();
            log::log('success: 访问:' . $ctrl_class . '\\' . $action);
        } else {
            log::log('error: 访问:' . $ctrl_class . '\\' . $action);
            throw new \Exception('找不到控制器' . $ctrl);
        }
    }

    /*
     * 自动加载类库
     * new \core\route();
     * $class = '\core\route';
     * WJSSK.'/core/route.php';
     * */
    static public function load($class)
    {
        if (isset($classMap[$class])) {
            return true;
        } else {
            $class = str_replace('\\', '/', $class);
            $file = WJSSK . '/' . $class . '.php';
            if (is_file($file)) {
                include $file;
                self::$classMap[$class] = $class;
            } else {
                return false;
            }
        }
    }

    public function assign($name, $value)
    {
        $this->assign[$name] = $value;
    }

    public function view($file)
    {
        $file = explode('.', $file);
        //$file_path = APP . '/view/' . implode('/', $file) . '.html';
        //if (is_file($file_path)) {
        $loader = new FilesystemLoader(APP . '/view');
        $twig = new Environment($loader, [
            'cache' => WJSSK . '/log/temp',
            'debug' => DEBUG
        ]);
        echo $twig->render(implode('/', $file) . '.html', $this->assign ? $this->assign : []);
        //} else {
        //     throw new \Exception('未找到模板文件' . PHP_EOL . $file);
        // }
    }
}